package com.warmheart.controller.platform;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.warmheart.base.annotation.AddOperateLog;
import com.warmheart.base.config.WhTransactionalControl;
import com.warmheart.base.session.SessionLocalUtils;
import com.warmheart.core.cors.enums.DateFormatEnum;
import com.warmheart.core.enums.OperationType;
import com.warmheart.entity.access.AccessPermission;
import com.warmheart.entity.platform.PlatformBase;
import com.warmheart.entity.user.UserRole;
import com.warmheart.entity.user.UserRoleMap;
import com.warmheart.impl.user.UserRoleMapService;
import com.warmheart.impl.user.UserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.warmheart.base.annotation.Auth;
import com.warmheart.base.annotation.Duplicate;
import com.warmheart.base.controller.BaseController;
import com.warmheart.base.page.PageInfo;
import com.warmheart.core.enums.ResultCode;
import com.warmheart.core.result.CommonResult;
import com.warmheart.core.util.OperatorUtil;
import com.warmheart.core.util.ParamMapUtil;
import com.warmheart.entity.platform.PlatformAccount;
import com.warmheart.service.platform.IPlatformAccountService;

/**
 * 
 * @ClassName: PlatformAccountController
 * @Description: 账号控制器
 * @author ZhangJianyang
 * @date 2025年06月16日 下午13:05:35
 *
 */
@RestController
@RequestMapping("/platform/platformAccount")
public class PlatformAccountController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(PlatformAccountController.class);

    // 注入账号service
    @Autowired(required = false)
    private IPlatformAccountService platformAccountService;
    @Autowired(required = false)
    private UserRoleMapService userRoleMapService;

    @Autowired(required = false)
    private UserRoleService userRoleService;

//    @Auth(verifyLogin = true)
//    @RequestMapping("/checkPermission")
//    public CommonResult<Map<String, Object>> checkPermission(HttpServletRequest request, HttpServletResponse response){
//        //获取当前登录用户
//        Integer adminId = SessionLocalUtils.getOperator().getLoginUser().getUserId();
//        //获取当前用户角色
//        UserRoleMap userRoleMap=new UserRoleMap();
//        userRoleMap.coBuilder().userId().eq(adminId);
//        UserRoleMap userRoleMap1 = userRoleMapService.selectOne(userRoleMap);
//        if(userRoleMap1==null){
//            return CommonResult.failed(ResultCode.FAILED, "用户角色关联表中没有此用户");
//        }
//        Integer roleId = userRoleMap1.getRoleId();
//        if(roleId==null){
//            return CommonResult.failed(ResultCode.FAILED, "角色id为空");
//        }
//        //获取当前用户身份名称
//        UserRole userRole=new UserRole();
//        userRole.coBuilder().id().eq(roleId);
//        UserRole userRole1 = userRoleService.selectOne(userRole);
//        if(userRole1==null){
//            return CommonResult.failed(ResultCode.FAILED, "角色表中没有此角色");
//        }
//        String name = userRole1.getName();
//        if(StringUtils.isBlank(name)){
//            return CommonResult.failed(ResultCode.FAILED, "角色名称为空");
//        }
//        if(!name.equals("系统管理员")){
//            return CommonResult.failed(ResultCode.FAILED, "不是系统管理员，你没有权限");
//        }
//        return CommonResult.success("权限验证成功");
//    }

    /**
     * 
     * @Title: listData
     * @Description: 查询账号列表数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @AddOperateLog(addLog = true,value = OperationType.QUERY)
    @Auth(verifyLogin = true)
    @GetMapping("/listDataByCondition")
    public CommonResult<Map<String, Object>> listDataByCondition(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);

        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();

        // 参数对象
        PlatformAccount platformAccount = new PlatformAccount();

        // 所属平台ID
        Integer platformId = ParamMapUtil.getInteger(jsonMap, "platformId");
        if (platformId != null) {
            platformAccount.setPlatformId(platformId);
        }

        // 账号类型
        String accountType = ParamMapUtil.getString(jsonMap, "accountType");
        if (StringUtils.isNotBlank(accountType)) {
            platformAccount.setAccountType(accountType);
        }

        // 用户名
        String username = ParamMapUtil.getString(jsonMap, "username");
        if (StringUtils.isNotBlank(username)) {
            platformAccount.setUsername(username);
        }

        // 每页记录数
        Integer pageSize = ParamMapUtil.getInteger(jsonMap, "pageSize");
        if (pageSize == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "每页记录数不能为空");
        }
        if (pageSize <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "每页记录数必须大于0");
        }
        platformAccount.setPageSize(pageSize);

        // 页码
        Integer pageId = ParamMapUtil.getInteger(jsonMap, "pageId");
        if (pageId == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "页码不能为空");
        }
        if (pageId <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "页码必须大于0");
        }
        platformAccount.setPageId(pageId);

        //platformAccount.setState("01");

        //只查询未过期的数据
        platformAccount.coBuilder().expiresTime(DateFormatEnum.yyyy_MM_dd_HH_mm_ss).gte(new Date());

        // 查询列表
        PageInfo<PlatformAccount> pageInfo = this.platformAccountService.queryByList(platformAccount);

        List<PlatformAccount> dataList = pageInfo.getData();
        Map<String, Object> pageMap = new HashMap<String, Object>();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (dataList != null && dataList.size() > 0) {

            // 整理返回数据
            for (PlatformAccount tempData : dataList) {
                Map<String, Object> tempMap = new HashMap<String, Object>();
                tempMap.put("id", tempData.getId());
                tempMap.put("platformId", tempData.getPlatformId());
                tempMap.put("resourceId", tempData.getResourceId());
                tempMap.put("accountType", tempData.getAccountType());
                tempMap.put("username", tempData.getUsername());
                tempMap.put("encryptedCredential", tempData.getEncryptedCredential());
                tempMap.put("encryptionIv", tempData.getEncryptionIv());
                tempMap.put("description", tempData.getDescription());
                tempMap.put("state", tempData.getState());
                tempMap.put("expiresTime", tempData.getExpiresTime());
                tempMap.put("createBy", tempData.getCreateBy());
                tempMap.put("cstCreate", tempData.getCstCreate());
                mapList.add(tempMap);
            }
        }
        pageMap.put("dataList", mapList);
        pageMap.put("rowCount", pageInfo.getPager().getRowCount());
        pageMap.put("pageCount", pageInfo.getPager().getPageCount());
        resultMap.put("pageMap", pageMap);
        return CommonResult.success("分页查询账号数据成功", resultMap);
    }


    /**
     * 
     * @Title: update
     * @Description: 修改账号数据进入页面
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @AddOperateLog(addLog = true,value = OperationType.QUERY)
    @Auth(verifyLogin = true)
    @GetMapping("/update")
    public CommonResult<Map<String, Object>> update(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);

        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();

        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该账号ID不可为空");
        }

        // 校验是否存在
        PlatformAccount checkPlatformAccount = platformAccountService.queryById(id);
        if (checkPlatformAccount == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该账号不存在");
        }
        Map<String, Object> tempMap = new HashMap<String, Object>();
        tempMap.put("id", checkPlatformAccount.getId());
        tempMap.put("platformId", checkPlatformAccount.getPlatformId());
        tempMap.put("resourceId", checkPlatformAccount.getResourceId());
        tempMap.put("accountType", checkPlatformAccount.getAccountType());
        tempMap.put("username", checkPlatformAccount.getUsername());
        tempMap.put("encryptedCredential", checkPlatformAccount.getEncryptedCredential());
        tempMap.put("encryptionIv", checkPlatformAccount.getEncryptionIv());
        tempMap.put("description", checkPlatformAccount.getDescription());
        tempMap.put("state", checkPlatformAccount.getState());
        tempMap.put("expiresTime", checkPlatformAccount.getExpiresTime());
        tempMap.put("createBy", checkPlatformAccount.getCreateBy());
        tempMap.put("cstCreate", checkPlatformAccount.getCstCreate());
        resultMap.put("dataMap", tempMap);
        return CommonResult.success("获取账号数据成功", resultMap);
    }

    /**
     * 
     * @Title: addSave
     * @Description: 添加保存账号数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @WhTransactionalControl
    @AddOperateLog(addLog = true,value = OperationType.INSERT)
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @PutMapping("/addSave")
    public CommonResult<Map<String, Object>> addSave(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);

        // 数据对象
        PlatformAccount platformAccount = new PlatformAccount();

        // 所属平台ID
        Integer platformId = ParamMapUtil.getInteger(jsonMap, "platformId");
        if (platformId != null) {
            platformAccount.setPlatformId(platformId);
        }

        // 账号类型
        String accountType = ParamMapUtil.getString(jsonMap, "accountType");
        if (StringUtils.isNotBlank(accountType)) {
            platformAccount.setAccountType(accountType);
        }

        // 用户名
        String username = ParamMapUtil.getString(jsonMap, "username");
        if (StringUtils.isNotBlank(username)) {
            platformAccount.setUsername(username);
        }

        //判断数据库中是否存在该平台
        PlatformAccount platformAccount1 = platformAccountService.selectOne(platformAccount);
        if(platformAccount1!=null){
            return CommonResult.failed(ResultCode.FAILED, "该平台已存在");
        }


        // 绑定的具体资源
        Integer resourceId = ParamMapUtil.getInteger(jsonMap, "resourceId");
        if (resourceId != null) {
            platformAccount.setResourceId(resourceId);
        }

        // 加密后的凭据
        String encryptedCredential = ParamMapUtil.getString(jsonMap, "encryptedCredential");
        if (StringUtils.isNotBlank(encryptedCredential)) {
            platformAccount.setEncryptedCredential(encryptedCredential);
        }

        // 加密向量
        String encryptionIv = ParamMapUtil.getString(jsonMap, "encryptionIv");
        if (StringUtils.isNotBlank(encryptionIv)) {
            platformAccount.setEncryptionIv(encryptionIv);
        }

        // 账号描述
        String description = ParamMapUtil.getString(jsonMap, "description");
        if (StringUtils.isNotBlank(description)) {
            platformAccount.setDescription(description);
        }

        // 是否激活
        String state = ParamMapUtil.getString(jsonMap, "state");
        if (StringUtils.isNotBlank(state)) {
            platformAccount.setState(state);
        }

        // 过期时间
        String expiresTime = ParamMapUtil.getString(jsonMap, "expiresTime");
        if (StringUtils.isNotBlank(expiresTime)) {

            // 过期时间
            Date expiresTimeRealValue = new SimpleDateFormat("yyyy-MM-dd").parse(expiresTime);
            platformAccount.setExpiresTime(expiresTimeRealValue);
        }


        try {
            OperatorUtil.addOper(platformAccount);
            platformAccountService.add(platformAccount);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("添加账号失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "添加账号失败");
        }

        return CommonResult.success("添加账号成功");
    }

    /**
     * 
     * @Title: updateSave
     * @Description: 修改保存账号数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @WhTransactionalControl
    @AddOperateLog(addLog = true,value = OperationType.UPDATE)
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @PostMapping("/updateSave")
    public CommonResult<Map<String, Object>> updateSave(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);

        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该账号ID不可为空");
        }

        // 是否存在校验
        PlatformAccount checkPlatformAccount = platformAccountService.queryById(id);
        if (checkPlatformAccount == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该账号不存在");
        }

        // 所属平台ID
        Integer platformId = ParamMapUtil.getInteger(jsonMap, "platformId");
        if (platformId != null) {
            checkPlatformAccount.setPlatformId(platformId);
        }

        // 绑定的具体资源
        Integer resourceId = ParamMapUtil.getInteger(jsonMap, "resourceId");
        if (resourceId != null) {
            checkPlatformAccount.setResourceId(resourceId);
        }

        // 账号类型
        String accountType = ParamMapUtil.getString(jsonMap, "accountType");
        if (StringUtils.isNotBlank(accountType)) {
            checkPlatformAccount.setAccountType(accountType);
        }

        // 用户名
        String username = ParamMapUtil.getString(jsonMap, "username");
        if (StringUtils.isNotBlank(username)) {
            checkPlatformAccount.setUsername(username);
        }

        // 加密后的凭据
        String encryptedCredential = ParamMapUtil.getString(jsonMap, "encryptedCredential");
        if (StringUtils.isNotBlank(encryptedCredential)) {
            checkPlatformAccount.setEncryptedCredential(encryptedCredential);
        }

        // 加密向量
        String encryptionIv = ParamMapUtil.getString(jsonMap, "encryptionIv");
        if (StringUtils.isNotBlank(encryptionIv)) {
            checkPlatformAccount.setEncryptionIv(encryptionIv);
        }

        // 账号描述
        String description = ParamMapUtil.getString(jsonMap, "description");
        if (StringUtils.isNotBlank(description)) {
            checkPlatformAccount.setDescription(description);
        }

        // 是否激活
        String state = ParamMapUtil.getString(jsonMap, "state");
        if (StringUtils.isNotBlank(state)) {
            checkPlatformAccount.setState(state);
        }

        // 过期时间
        String expiresTime = ParamMapUtil.getString(jsonMap, "expiresTime");
        if (StringUtils.isNotBlank(expiresTime)) {

            // 过期时间
            Date expiresTimeRealValue = new SimpleDateFormat("yyyy-MM-dd").parse(expiresTime);
            checkPlatformAccount.setExpiresTime(expiresTimeRealValue);
        }

        try {
            OperatorUtil.updateOper(checkPlatformAccount);
            platformAccountService.updateIncludeAll(checkPlatformAccount);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("修改账号失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "修改账号失败");
        }

        return CommonResult.success("修改账号成功");
    }

    /**
     * 
     * @Title: delete
     * @Description: 删除账号数据
     * @author ZhangJianyang
     * @date 2025年06月16日 下午13:05:35
     * @param request
     * @param response
     * @throws Exception
     */
    @AddOperateLog(addLog = true,value = OperationType.DELETE)
    @Auth(verifyLogin = true)
    @DeleteMapping("/delete")
    public CommonResult<Map<String, Object>> delete(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该账号ID不可为空");
        }

        // 是否存在校验
        PlatformAccount checkPlatformAccount = platformAccountService.queryById(id);
        if (checkPlatformAccount == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该账号不存在");
        }

        String state = checkPlatformAccount.getState();
        if(!state.equals("01")){
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "删除密钥失败,该密钥不属于激活状态");
        }
        else{
            checkPlatformAccount.setState("02");
        }

        try {
            OperatorUtil.updateOper(checkPlatformAccount);
            platformAccountService.updateIncludeAll(checkPlatformAccount);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("删除账号失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "删除账号失败");
        }

        return CommonResult.success("删除账号成功");
    }

    //批量删除，彻底从数据库中删除
    @Auth(verifyLogin = true)
    @DeleteMapping("/deleteBatch")
    public CommonResult<Map<String, Object>> deleteBatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        List<Integer> ids = ParamMapUtil.getIntegerList(jsonMap, "ids");
        if (ids == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该批准记录ID不可为空");
        }
        List<PlatformAccount> platformAccounts = platformAccountService.queryByIdList(ids);
        if (platformAccounts == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该批准记录不存在");
        }
        try {
            platformAccountService.deleteByIdList(ids);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("删除访问记录失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "删除批准记录失败");
        }

        return CommonResult.success("删除批准记录成功");
    }
}
